<template>
    <div id="user-main">
        <div class="userList-herd">
            <div>
                <el-form :inline="true" :model="paging" class="demo-form-inline">
                    <el-form-item v-for="(item, index) in menuBtns" :key="index">
                        <el-button v-if="item.icon == CREATE || item.icon == DELETE" :type="item.icon"
                            @click="clickBtn(item.icon)"> {{ item.menuName }}</el-button>
                    </el-form-item>
                    <el-form-item>
                        <el-input v-model="paging.userName" placeholder="用户名称"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button @click="onReSetSeach">重置</el-button>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="init">查询</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </div>

        <div class="user-body">
            <el-table ref="multipleTable" tooltip-effect="dark" @selection-change="handleSelectionChange"
                :data="pagingData.totalList" style="width: 100%">
                <el-table-column type="selection" width="55" :selectable="checkboxInit"> </el-table-column>
                <el-table-column prop="id" label="id" width="100" align="center"></el-table-column>
                <el-table-column prop="nickName" label="用户昵称" width="180" align="center"></el-table-column>
                <el-table-column prop="userName" label="用户名" width="180" align="center"></el-table-column>
                <el-table-column prop="avatar" label="头像" width="100" align="center">
                    <template slot-scope="scope">
                        <image-preview :src="scope.row.avatar" :width="50" :height="50" />
                    </template>
                </el-table-column>
                <!-- <el-table-column label="秘钥管理" width="100" align="center">
                    <template slot-scope="scope">
                        <el-button @click="handleClick('VIEW_KEY', scope.row)" type="text" size="small">查看</el-button>
                    </template>
                </el-table-column> -->
                <el-table-column prop="isDel" label="是否开启" width="180" align="center">
                    <template slot-scope="scope">
                        <el-tag v-if="!scope.row.isDel" type="success">开启</el-tag>
                        <el-tag v-else type="info">关闭</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="userType" label="用户类型" width="180" align="center">
                    <template slot-scope="scope">
                        <el-tag v-if="scope.row.userType == '00'">系统</el-tag>
                        <el-tag v-if="scope.row.userType == '01'" type="success">默认</el-tag>
                        <el-tag v-if="scope.row.userType == '02'" type="info">普通</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="phone" label="手机号" width="180" align="center">
                    <template slot-scope="scope">
                        <div v-if="scope.row.phone">{{ scope.row.phone }}</div>
                        <div v-else>暂无</div>
                    </template>
                </el-table-column>
                <el-table-column prop="email" label="邮箱" width="180" align="center">
                    <template slot-scope="scope">
                        <div v-if="scope.row.email">{{ scope.row.email }}</div>
                        <div v-else>暂无</div>
                    </template>
                </el-table-column>
                <el-table-column fixed="right" label="操作" min-width="120" align="center">
                    <template slot-scope="scope">
                        <!-- 默认用户和列表 -->
                        <div v-if="isSysDef(userInfo.userType) && !isSysDef(scope.row.userType)">
                            <div class="btns" v-for="(item, index) in menuBtns" :key="index">
                                <el-button type="text" size="small" v-if="item.icon == UPDATE || item.icon == DELETE"
                                    @click="handleClick(item.perms, scope.row)" :style="getButtonStyle(item.icon)">{{
                                        item.menuName }}</el-button>
                            </div>
                        </div>
                        <!-- 不是默认用户 -->
                        <div
                            v-if="!isSysDef(userInfo.userType) && scope.row.userType == '02' && scope.row.id != userInfo.userId">
                            <div class="btns" v-for="(item, index) in menuBtns" :key="index">
                                <el-button type="text" size="small" v-if="item.icon == UPDATE || item.icon == DELETE"
                                    @click="handleClick(item.perms, scope.row)" :style="getButtonStyle(item.icon)">{{
                                        item.menuName }}</el-button>
                            </div>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
            <div v-if="pagingData && pagingData.totalList && pagingData.totalList.length > 0">
                <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                    :current-page="pagingData.currentPage" :page-sizes="[10, 20, 30, 40]" :page-size="10"
                    layout="total, sizes, prev, pager, next, jumper" :total="pagingData.total">
                </el-pagination>
            </div>
        </div>

        <el-dialog title="添加用户" :visible.sync="dialogTableAddVisible">
            <el-form :model="addForm" ref="addForm">
                <el-form-item label="用户昵称" prop="nickName" :label-width="formLabelWidth" :required="true">
                    <el-input v-model="addForm.nickName" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="用户名" prop="userName" :label-width="formLabelWidth" :required="true">
                    <el-input v-model="addForm.userName" autocomplete="off" placeholder="只能输入字母和数字"></el-input>
                </el-form-item>
                <el-form-item label="用户密码" prop="passWord" :label-width="formLabelWidth" :required="true">
                    <el-input v-model="addForm.passWord" autocomplete="off" placeholder="字母和数字和特殊字符"
                        show-password></el-input>
                </el-form-item>
                <el-form-item label="用户头像" prop="avatar" :label-width="formLabelWidth">
                    <image-upload :fileSize="10" v-model="addForm.avatar" :limit="1" />
                </el-form-item>
                <el-form-item label="邮件地址" prop="email" :label-width="formLabelWidth">
                    <el-input v-model="addForm.email" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="联系方式" prop="phone" :label-width="formLabelWidth">
                    <el-input v-model="addForm.phone" autocomplete="off"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="handleCancel">取 消</el-button>
                <el-button type="primary" @click="onSave">保存</el-button>
            </div>
        </el-dialog>

        <el-dialog title="编辑用户" :visible.sync="dialogTableEditVisible">
            <el-form :model="editForm" ref="editForm">
                <el-form-item label="用户昵称" prop="nickName" :label-width="formLabelWidth" :required="true">
                    <el-input v-model="editForm.nickName" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="用户名" prop="userName" :label-width="formLabelWidth" :required="true">
                    <el-input v-model="editForm.userName" autocomplete="off" :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="用户头像" prop="avatar" :label-width="formLabelWidth">
                    <image-upload :fileSize="10" v-model="editForm.avatar" :limit="1" />
                </el-form-item>
                <el-form-item label="联系方式" prop="phone" :label-width="formLabelWidth">
                    <el-input v-model="editForm.phone" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="邮件地址" prop="email" :label-width="formLabelWidth">
                    <el-input v-model="editForm.email" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="用户密码" prop="passWord" :label-width="formLabelWidth">
                    <el-input v-model="editForm.passWord" autocomplete="off" placeholder="*****" show-password></el-input>
                </el-form-item>
                <el-form-item label="是否开启" :label-width="formLabelWidth">
                    <el-switch v-model="editForm.isDel" active-color="#13ce66" inactive-color="#ff4949" :active-value="0"
                        :inactive-value="1">
                    </el-switch>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="handleCancel">取 消</el-button>
                <el-button type="primary" @click="onEdit">保存</el-button>
            </div>
        </el-dialog>

        <el-dialog title="分配角色" :visible.sync="dialogTableBindVisible">
            <el-select v-model="bind.roleIds" multiple placeholder="请选择">
                <el-option v-for="(item, index) in roleListData" :key="index" :label="item.name" :value="item.id">
                </el-option>
            </el-select>
            <div slot="footer" class="dialog-footer">
                <el-button @click="handleCancel">取 消</el-button>
                <el-button type="primary" @click="onBindRole">保存</el-button>
            </div>
        </el-dialog>

        <!-- <el-dialog title="秘钥管理" :visible.sync="dialogTableBindVisibleKey">
            <el-form :model="viewKey" ref="viewKey">
                <el-form-item label="accessKey" prop="accessKey" :label-width="formLabelWidth">
                    <el-input v-model="viewKey.accessKey" autocomplete="off" :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="secretKey" prop="secretKey" :label-width="formLabelWidth">
                    <el-input v-model="viewKey.secretKey" autocomplete="off" :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="到期时间" prop="authEndTime" :label-width="formLabelWidth" :required="true">
                    <el-date-picker v-model="viewKey.authEndTime" type="datetime" format="yyyy-MM-dd HH:mm:ss"
                        placeholder="选择日期时间" :clearable="true"></el-date-picker>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="onEditKey">更新秘钥</el-button>
            </div>
        </el-dialog> -->
    </div>
</template>
  
<script>
import { mapState } from 'vuex';
import { getSecondStr, isSysDef } from "@/common/utils/strUtil";
import { menuBtnByParentId } from "@/common/utils/MenuBtnUtils";
import { userListPaging, createUser, deleteUser, updateUser, userBindRole, userGetRole } from "@/common/api/user";
import { roleListPaging } from "@/common/api/role";
import { dateTimeInMilliseconds } from "@/common/utils/formatTime";
import { CREATE, UPDATE, DELETE, UNBIND, BIND } from "@/common/constant/Const";
export default {
    components: {
    },
    data() {
        return {
            CREATE,
            UPDATE,
            DELETE,
            UNBIND,
            BIND,
            menuBtns: [],
            paging: {
                currentPage: 1,
                pageSize: 10,
            },
            pagingData: {},
            dialogTableAddVisible: false,
            addForm: {
            },
            formLabelWidth: "120px",
            dialogTableEditVisible: false,
            editForm: {},
            deleteForm: {
                ids: [],
            },
            unBind: {},
            dialogTableBindVisible: false,
            bind: {
                roleIds: [],
            },
            roleListData: [],
            viewKey: {
                authEndTime: null,
            },
            dialogTableBindVisibleKey: false,
            eidtDeptDisPlay: false,
            userInfo: JSON.parse(sessionStorage.getItem("userInfo")),
        };
    },
    computed: {
        ...mapState({
            menuItem: state => state.tab.menuItem,
            // isSelectedDept: state => state.tab.isSelectedDept,
            // userInfo: state => state.tab.userInfo,
        }),
    },
    mounted() {
        this.getMenuBtn(this.menuItem.id);
        this.init();
        roleListPaging({
            currentPage: 1,
            pageSize: 100,
        }).then((resp) => {
            if (resp) {
                this.roleListData = resp.data.totalList.filter((item => item.isDel != 1 && item.roleType != "00"));
            }
        })
    },
    methods: {
        getSecondStr,
        isSysDef,
        menuBtnByParentId,
        dateTimeInMilliseconds,
        getMenuBtn(data) {
            menuBtnByParentId(data).then((respData) => {
                this.menuBtns = respData;
            }).catch((error) => {
                console.error("Error fetching menu buttons:", error);
            });
        },
        // 查询数据
        init() {
            userListPaging(this.paging).then((resp) => {
                if (resp) {
                    this.pagingData = resp.data;
                }
            });
        },
        clickBtn(data) {
            console.log(data);
            if (CREATE == data) {
                this.dialogTableAddVisible = true;
            }
            if (UPDATE == data) {
            }
            if (DELETE == data) {
                this.$confirm('此操作将永久删除, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.onRemove();
                }).catch(() => {
                    this.deleteForm.ids = [];
                    this.$refs.multipleTable.clearSelection();
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            }
        },
        onRemove() {
            deleteUser(this.deleteForm).then((resp) => {
                if (resp) {
                    this.init();
                    this.handleCancel();
                }
            })
        },
        // 重置
        onReSetSeach() {
            this.paging = {
                currentPage: 1,
                pageSize: 10,
            };
            this.init();
        },
        // 分页回调
        handleSizeChange(val) {
            this.paging.pageSize = val;
            this.init()
        },
        // 分页回调
        handleCurrentChange(val) {
            this.paging.currentPage = val;
            this.init()
        },
        // 多选表时的回调
        handleSelectionChange(val) {
            this.deleteForm.ids = val.map(item => item.id);
        },
        // 是否可选择表格
        checkboxInit(row, index) {
            if (row.id == this.userInfo.userId) {
                return false;
            }
            if (isSysDef(this.userInfo.userType)) {
                return !isSysDef(row.userType);
            }
            return row.userType == '02';
        },
        // 同意取消
        handleCancel() {
            this.dialogTableAddVisible = false;
            this.addForm = {
            };

            this.dialogTableEditVisible = false;
            this.editForm = {};
            this.deleteForm.ids = [];
            this.unBind = {};
            this.dialogTableBindVisible = false;
            this.bind = { roleIds: [] };

            this.viewKey = {
                authEndTime: null,
            };
            this.dialogTableBindVisibleKey = false;
            // this.$refs.selectedDept.reSetDef();
            this.eidtDeptDisPlay = false;
        },
        // 新增用户
        onSave() {
            // this.addForm.deptId = this.isSelectedDept.id == '' ? null : this.isSelectedDept.id;
            createUser(this.addForm).then((resp) => {
                if (resp) {
                    this.init();
                    this.handleCancel();
                }
            });
        },
        // 检查是否需要应用红色字体
        getButtonStyle(perms) {
            if (this.DELETE == perms) {
                return { color: 'red' };
            }
            if (this.UNBIND == perms) {
                return { color: '#E6A23C' };
            }
            // 默认样式（可以是空对象，或者你可以设置其他样式）
            return {};
        },
        // 点击事件
        handleClick(type, data) {
            console.log(type, name);
            if (type == "EDIT") {
                this.editForm = { ...data };
                this.dialogTableEditVisible = true;
            }
            if (type == 'BIND_ROLE') {
                userGetRole(data.id).then((res) => {
                    if (res) {
                        this.bind.roleIds = res.data;
                        this.bind.id = data.id;
                        this.dialogTableBindVisible = true;
                    }
                })
            }
            if (type == "DELETE") {
                this.$confirm('此操作将永久删除, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.deleteForm.ids.push(data.id);
                    this.onRemove();
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            }
        },
        // 修改保存
        onEdit() {
            // this.editForm.deptId = this.isSelectedDept.id == '' ? -1 : this.isSelectedDept.id;
            updateUser(this.editForm).then((resp) => {
                if (resp) {
                    this.init();
                    this.handleCancel();
                }
            });
        },
        // 取消绑定租户角色
        onUnBind() {
            unbindTenantRole(this.unBind).then((resp) => {
                if (resp) {
                    this.init();
                    this.handleCancel();
                }
            });
        },
        // 分配角色
        onBindRole() {
            userBindRole(this.bind).then((resp) => {
                if (resp) {
                    this.init();
                    this.handleCancel();
                }
            })
        },
        // 更新密钥
        onEditKey() {
            this.$confirm('此操作将立即更新秘钥,原有秘钥将立即失效, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.viewKey.authEndTime = this.dateTimeInMilliseconds(this.viewKey.authEndTime);
                authUser(this.viewKey).then((resp) => {
                    if (resp) {
                        this.init();
                        this.handleCancel();
                    }
                });
            }).catch(() => {
                this.viewKey = {
                    authEndTime: null,
                };
                this.dialogTableBindVisibleKey = false;
                this.$message({
                    type: 'info',
                    message: '已取消更新'
                });
            });

        },
    },
};
</script>
<style lang="less" scoped></style>